<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <title>画缘</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        /* 增加字体大小 */
        body {
            font-size: 24px;
            /* 您可以根据需要调整这个值 */
        }

        .container {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-evenly;
            align-items: flex-start;
        }

        .image-container {
            position: relative;
            z-index: 0;
            width: 30%;
            border: 2px solid rgb(206, 185, 185);
            border-radius: 6px;
            margin-bottom: 10px;
            aspect-ratio: 9/16;
        }

        .red-dot {
            position: absolute;
            top: -6px;
            right: -6px;
            z-index: 1;
            width: 40px;
            height: 40px;
            background-color: red;
            border-radius: 50%;
        }

        .change-button {
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            z-index: 1;
            background-color: #945858;
            border-radius: 10px;
            width: 200px;
            font-size: 48px;
            color: wheat;
            display: none;
            justify-content: center;
            align-items: center;
        }

        .last-online {
            position: absolute;
            top: 0;
            left: 50%;
            transform: translateX(-50%);
            z-index: 1;
            font-size: 44px;
            width: 100%;
            border-radius: 8px;
            text-align: center;
            background-color: #d3a6a6;
            display: none;
        }

        .bottom-menu {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 10px;
            font-size: 90px;
        }

        .bottom-menu div {
            margin: 0 20px;
        }

        .menu-item {
            cursor: pointer;
            /* 鼠标指针变为手型 */
        }

        .menu-item:active {
            transform: scale(0.85);
            /* 点击时缩小元素 */
            transition: transform 0.1s ease;
            /* 添加过渡效果 */
        }

        img {
            display: block;
        }
    </style>
</head>

<body>
    <div class="container">

    </div>
    <div style="height: 120px;"></div>
    <div class="bottom-menu">
        <div id="settings-icon" class="menu-item"><i class="fas fa-cog"></i></div>
        <div class="menu-item" id="refresh-button"><i class="fas fa-sync-alt"></i></div>
        <div class="menu-item"><i class="fas fa-home"></i></div>
        <div class="menu-item"><i class="fas fa-question-circle"></i></div>
        <div class="menu-item"><i class="fas fa-info-circle"></i></div>

    </div>
    <script>
        //没推荐好友时加载的图片
        let noFriendsImg = createImageWithText("空缺", 360, 640, 60, "black", 0.2);
        let newFriendsImg = createImageWithText("新好友", 360, 640, 60, "black", 0.2);
        let errorImg = createImageWithText("加载失败", 360, 640, 60, "black", 0.2);
        let removedImg = createImageWithText("对方已将你移除", 360, 640, 60, "black", 0.2);
        let friendData = [];
        //获取当前用户信息
        let user = JSON.parse(localStorage.getItem("user"));
        //网页加载
        window.onload = function () {
            if (user == null) {
                window.location.href = "../index.html";
            } else {
                fetch("getRecommend.php?userId=" + user.id)
                    .then(response => {
                        console.log(response);
                        if (!response.ok) {
                            throw new Error('Network response was not ok');
                        }
                        return response.json();
                    })
                    .then(data => {
                        // 处理返回的数据
                        console.log(data);
                        friendData = data;
                        // 遍历数组，生成模块并添加到容器中
                        const container = document.querySelector('.container');
                        for (let i = 0; i < data.length; i++) {
                            const module = generateModule(user.id, data[i][0], data[i][1], data[i][2], i);
                            container.appendChild(module);
                        }
                    })
                    .catch(error => {
                        console.error('There has been a problem with your fetch operation:', error);
                    });
            }
        }
        // 定义一个函数来计算时间差
        function timeAgo(sendTime) {
            const now = new Date();
            const sendTimeDate = new Date(sendTime);
            const str = "在线"
            const timeDiff = now - sendTimeDate; // 时间差值（毫秒）
            const seconds = Math.floor(timeDiff / 1000); // 总秒数
            const minutes = Math.floor(seconds / 60); // 总分钟数
            const hours = Math.floor(minutes / 60); // 总小时数
            const days = Math.floor(hours / 24); // 总天数

            if (days >= 10 * 365) { // 大于等于10年
                return "对方已将你移除";
            } else if (days >= 365) { // 大于等于1年
                return strMath.floor(days / 365) + "年前"+str;
            } else if (days >= 30) { // 大于等于1个月
                return  Math.floor(days / 30) + "个月前"+str;
            } else if (days >= 1) { // 大于等于1天
                return  days + "天前"+str;
            } else if (hours >= 1) { // 大于等于1小时
                return  hours + "小时前"+str;
            } else if (minutes >= 1) { // 大于等于1分钟
                return  minutes + "分钟前"+str;
            } else { // 小于1分钟
                return  seconds + "秒前"+str;
            }
        }
        //定义一个函数来控制消息红点的显示隐藏
        function showRedDot(key, sendTime1) {
            //sendTime转时间戳
            let sendTime = new Date(sendTime1).getTime() / 1000;
            //获取key的本地时间戳缓存
            const sendTimeCache = localStorage.getItem(key);
            console.log(key, sendTime1, sendTime, sendTimeCache);
            //如果sendTimeCache存在且大于sendTime，则隐藏红点
            if (sendTimeCache && sendTimeCache >= sendTime) {
                return false;
            } else {
                //如果sendTimeCache不存在或小于sendTime，则显示红点
                return true;
            }
        }
        // 定义一个函数来动态生成HTML模块
        let changeButtons = [];
        let lastOnlines = [];
        let redDots = [];
        // 获取刷新按钮元素
        const refreshButton = document.getElementById('refresh-button');

        // 添加点击事件监听器
        refreshButton.addEventListener('click', function () {
            // 刷新当前页面
            location.reload();
        });
        function generateModule(userId, friendId, onlineTime, sendTime, index) {
            const src = [userId, friendId].sort().join('');
            // console.log(src);
            // 创建一个新的div元素，并添加image-container类
            const imageContainer = document.createElement('div');
            imageContainer.classList.add('image-container');
            // 设置自定义数据属性
            if (friendId) {
                imageContainer.dataset.userIdfriendId = src;
            }

            // 创建一个img元素，并设置src属性
            const img = document.createElement('img');
            img.style.width = "100%";

            // 创建一个div元素，并添加red-dot类
            const redDot = document.createElement('div');
            redDot.classList.add('red-dot');
            redDots.push(redDot);

            // 创建一个div元素，并添加change-button类
            const changeButton = document.createElement('div');
            changeButton.classList.add('change-button');
            changeButton.dataset.index = index;
            if (friendId) {
                changeButton.textContent = "换一位";
            } else {
                changeButton.textContent = "";
                redDot.style.display = 'none';
            }

            // 将changeButton添加到changeButtons数组中
            changeButtons.push(changeButton);

            // 创建一个div元素，并添加last-online类
            const lastOnline = document.createElement('div');
            lastOnline.classList.add('last-online');
            if (friendId) {
                if (sendTime) {
                    img.src = "chatPng/" + src + ".png";
                    redDot.style.display = showRedDot(src, sendTime) ? 'block' : 'none';
                    if (onlineTime == "1") {
                        lastOnline.textContent = "对方已将你移除";
                    } else {
                        lastOnline.textContent = timeAgo(onlineTime);
                    }
                } else {
                    redDot.style.display = 'none';
                    lastOnline.textContent = "发一条消息吧"
                    img.src = newFriendsImg;
                }
            } else {
                lastOnline.textContent = "";
                img.src = noFriendsImg;
            }
            //lastOnline.textContent = `上次在线：${onlineTime}（年/月/天/小时/分钟/秒）前`;
            // 将lastOnline添加到lastOnlines数组中
            lastOnlines.push(lastOnline);

            // 将所有子元素添加到image-container中
            imageContainer.appendChild(img);
            imageContainer.appendChild(redDot);
            imageContainer.appendChild(changeButton);
            imageContainer.appendChild(lastOnline);

            // 添加点击事件监听器
            imageContainer.addEventListener('click', function () {
                // alert('点击了模块，userId + friendId =' + this.dataset.userIdfriendId);
                //如果定义了userIdfriendId，则跳转到链接huaban.html,参数f，在新窗口打开
                if (this.dataset.userIdfriendId) {
                    localStorage.setItem(this.dataset.userIdfriendId, Date.now() / 1000);
                    redDot.style.display = 'none';
                    window.open("huaban.html?f=" + this.dataset.userIdfriendId + "&t=1");
                }
            });
            // 添加change-button的点击事件监听器
            changeButton.addEventListener('click', function () {
                //阻止事件冒泡
                event.stopPropagation();
                let index = this.dataset.index;
                // alert('点击了换一位按钮，friendId = ' + index + "-" + friendData[index][0]);
                fetch("remove_recommend_friend.php?userId=" + user.id + "&friendId=" + friendData[index][0]).then(response => {
                    console.log(response);
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.text();
                }).then(data => {
                    // 处理返回的数据
                    // alert(data);
                    if (data == "1") {
                        lastOnlines[index].textContent = "";
                        changeButtons[index].textContent = "";
                        redDots[index].style.display = 'none';
                    }
                })
            });
            // 返回生成的image-container元素
            return imageContainer;
        }

        function createImageWithText(text, width, height, fontSize, color, opacity) {
            // 创建一个新的canvas元素
            const canvas = document.createElement('canvas');
            canvas.width = width;
            canvas.height = height;

            // 获取canvas的2D上下文
            const ctx = canvas.getContext('2d');

            // 设置半透明背景
            ctx.fillStyle = 'rgba(255, 255, 255, 0.95)'; // 半透明白色
            ctx.fillRect(0, 0, width, height);

            // 设置字体样式
            ctx.font = `${fontSize}px Arial`;
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.fillStyle = color;



            // 设置文字的透明度
            ctx.globalAlpha = opacity;

            // 在canvas上绘制文本
            ctx.fillText(text, width / 2, height / 2);

            return canvas.toDataURL('image/jpeg');
        }
        // 获取设置图标元素
        const settingsIcon = document.getElementById('settings-icon');
        // 定义一个变量来跟踪显示状态
        let isHidden = true;

        // 添加点击事件监听器
        settingsIcon.addEventListener('click', function () {
            // 切换显示状态
            isHidden = !isHidden;

            // 遍历所有的change-button和last-online元素，并设置显示或隐藏
            changeButtons.forEach(button => {
                button.style.display = isHidden ? 'none' : 'flex';
            });

            lastOnlines.forEach(online => {
                online.style.display = isHidden ? 'none' : 'block';
            });
        });
    </script>
</body>

</html>